<template>
  <div class="page">
    <div class="page-top app-container">
      <div>商品标签销售分析</div>

      <div class="btn-group">
        <el-button plain v-hasPermi="['org:goods:export']" @click="handleExport">
          导出数据
        </el-button>

        <el-radio-group v-model="radioValue">
          <el-radio-button label="当天" />
          <el-radio-button label="最近7天" />
          <el-radio-button label="最近30天" />
        </el-radio-group>

        <el-date-picker
          style="width: 260px"
          v-model="state.timeRange"
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          @calendar-change="dateChange"
          :clearable="false"
        />
      </div>
    </div>
    <div class="app-container">
      <div class="charts">
        <PieChart class="pie-chart" :data="pieData" name="分类名称" />
      </div>
      <el-table v-loading="state.loading" :data="tableList">
        <el-table-column label="分类名称" align="center" prop="name" />
        <el-table-column label="销售数量" align="center" prop="sellCount" />
        <el-table-column label="数量比例(%)" align="center" prop="countScale" />
        <el-table-column label="销售金额(元)" align="center" prop="salesAmount" />
        <el-table-column label="金额比例(%)" align="center" prop="amountRatio" />
      </el-table>

      <pagination
        v-show="state.total > 0"
        :total="state.total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup name="ComboAnalysis">
import { parseTime } from '@/utils/tools'
import PieChart from '../components/Piechart'
import { onMountedOrActivated } from '@/hooks/common'
import { getGoodsReport } from '@/api/order/index'

let firstLoad = true
const { proxy } = getCurrentInstance()
const radioValue = ref('最近30天')
const tableList = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
const state = reactive({
  total: 0,
  loading: false,
  timeRange: []
})

const pieData = computed(() => {
  const map = new Map()
  tableList.value?.map((item) => {
    const { name, sellCount: value = 0 } = item

    if (name) {
      const obj = map.get(name)
      if (obj) {
        obj.value += +value
      } else {
        map.set(name, { name, value })
      }
    }
  })

  return [...map.values()]
})

watchEffect(() => handleDateRange(radioValue.value))
watchEffect(() => {
  const [startTime, endTime] = state.timeRange
  queryParams.value.startTime = startTime ? `${startTime} 00:00:00` : ''
  queryParams.value.endTime = endTime ? `${endTime} 23:59:59` : ''

  if (firstLoad) return
  getList()
})

const dateChange = () => (radioValue.value = '')
function handleDateRange(val) {
  const end = parseTime(new Date(), '{y}-{m}-{d}')
  const start = new Date()
  switch (val) {
    case '最近30天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}'), end]
      break
    case '最近7天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}'), end]
      break
    case '当天':
      state.timeRange = [parseTime(start, '{y}-{m}-{d}'), end]
      break
    default:
      break
  }
}

async function getList() {
  console.log(123)
  state.loading = true

  try {
    const r = await getGoodsReport(queryParams.value)
    tableList.value = r?.rows ?? []
    state.total = r?.total ?? 0
  } finally {
    state.loading = false
  }

  firstLoad = false
}

/** 导出按钮操作 */
function handleExport() {
  const { startTime, endTime } = queryParams.value
  proxy.download(
    'org/orderList/TagDerive',
    { startTime, endTime },
    `商品标签销售分析${new Date().getTime()}.xlsx`
  )
}
/**init +  onActivated*/
onMountedOrActivated(getList)
</script>

<style lang="scss" scoped>
.page {
  min-width: 960px;
  overflow-x: scroll;
}
.page-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  align-self: stretch;
  font-size: 16px;
  height: 60px;
  background: var(--el-color-info-light-8);
  .btn-group {
    display: flex;
    align-items: center;
  }
  .el-radio-group {
    margin: 0 10px;
  }
}

.charts {
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 100%;
  .pie-chart {
    flex: 1;
    min-width: 350px;
    height: 450px;
    margin-right: 20px;
  }
}
</style>
